<template>

  <!-- <p>用户信息</p> -->
  <div class="userInfo">
    <p>头像</p>
    <img title="点击更换头像" @click="setUserAvatarApi" class="logoAvatar" :src="userInfo.logo" alt="">
  </div>
  <input style="visibility: hidden;" ref="avatarInput" type="file" @change="uploadImage">
  <div class="userInfoList">
    <p>账号绑定
      <span>
        绑定手机号和微信，账号更安全且登录方便; 为保证账号安全，绑定账号需进行二次验证。
      </span>
    </p>
    <ul>
      <li>
        <div>
          <img src="../../assets/img/recharge/Bind-WeChat.png" alt="">
          <div>绑定微信</div>
          <span>{{ userInfo.isWechat === '1' ?'已绑定':'未绑定' }}</span>
        </div>
        <div class="red" @click="canceWeChat">更换</div>
      </li>
      <li>
        <div>
          <img src="../../assets/img/垃圾桶.png" alt="">
          <div>绑定手机号</div>
          <span>{{ userInfo.mobile ? userInfo.mobile : '未绑定手机号' }}</span>
        </div>
        <div class="red" @click="setSMSPhoneNumber">更换</div>
      </li>
    </ul>
  </div>
  <div class="userInfoList">
    <p>
      密码设置
      <span>
        设置密码，账号更安全; 为保证账号安全，设置密码需进行二次验证。
      </span>
    </p>
    <ul>
      <li>
        <div>
          <img src="../../assets/img/垃圾桶.png" alt="">
          <div>密码</div>
          <span class="red">*****</span>
        </div>
        <div @click="setSmSCheckPwdModelStart">修改</div>
      </li>
      <li>
        <div>
          <img src="../../assets/img/垃圾桶.png" alt="">
          <div>注销账号</div>
          <span class="red">您的账号一旦被注销成功将不可恢复</span>
        </div>
        <div @click="centerDialogVisible=true" class="red">注销
        </div>
      </li>
    </ul>
  </div>

  <!-- 微信扫码绑定 -->
  <xwDialog v-model:dialogVisible="dialogVisible">
    <template #title>
      <h4 style="text-align: center;">请使用微信扫码绑定,有BUG</h4>
    </template>
    <div id="code"></div>
  </xwDialog>
  <!-- 更换手机号 -->
  <xwDialog v-model:dialogVisible="setPhonenModel">
    <template #title>
      <h4 style="text-align: center;">更改手机号</h4>
    </template>
    <el-form ref="formRef" style="width: 100%" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item>
        <h4>当前手机号:{{userInfo.mobile}}</h4>
      </el-form-item>
      <el-form-item prop="phone">
        <el-input placeholder="请输入新手机号" v-model="ruleForm.phone" type="text" />
      </el-form-item>
      <el-form-item prop="phoneCode">
        <el-input placeholder="请输入验证码" v-model="ruleForm.phoneCode" type="text">
          <template #append>
            <el-button @click="sendPhoneCode(formRef)" :color="setTimer.timerShow?'red':''"
              :disabled="setTimer.timerShow" type="primary">{{ setTimer.timerShow === true ? ('重新发送 ' + setTimer.outTime
              + ' 秒') : ('获取验证码') }}
            </el-button>
          </template>
        </el-input>
      </el-form-item>
    </el-form>

    <SlideSplit v-if=rulesImgShow :smallHeight='imgInfo.smallHeight' :w='imgInfo.bigWidth' :h='imgInfo.bigHeight'
      :l='imgInfo.smallWidth' :bigImg='imgInfo.bigImageBase64' :smImg='imgInfo.smallImageBase64' @request-event="getIMG"
      @sliderJudge="mouseMoveEnd" style="position: absolute; z-index: 99;"></SlideSplit>
    <template #footer>
      <el-button :disabled="ruleForm.phoneCode ===''" color="#c90000" style="width: 100%;"
        @click="checkPhoneCode ">验证</el-button>
    </template>
  </xwDialog>
  <!-- 获取短信验证 -->
  <xwDialog v-model:dialogVisible="getSmSCheckPwd">
    <div class="setPwd">
      <div>身份验证</div>
      <p class="pwdTip">为了保护您的账号安全，请验证身份 验证成功后进行下一步操作</p>
      <el-form>
        <div class="mymobile">
          使用手机号:{{ userInfo.mobile }}
        </div>
        <el-form-item style="display: flex;">
          <el-input v-model="SmsCodePwd" placeholder="请输入验证码" >
            <template #append>
              <el-button @click="getSmSCheckPwdApi" :color="setTimer.timerShow ? 'red' : ''"
                :disabled="setTimer.timerShow" type="primary">{{ setTimer.timerShow === true ? ('重新发送 ' +
                setTimer.outTime
                + ' 秒') : ('获取验证码') }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-button style="width: 100%;" color="#c90000" @click="checkSmsCodePwdApi">验证</el-button>

    </div>

  </xwDialog>
  <!-- 修改密码 -->
  <xwDialog v-model:dialogVisible="passwordModel">
    <div class="setPwd">
      <div>身份验证</div>
      <p class="pwdTip">为了保护您的账号安全，请验证身份 验证成功后进行下一步操作</p>
      <el-form ref="formRefPwd" :model="pwdData" :rules="ruleFormPwd">
        <el-form-item prop="password">
          <el-input v-model="pwdData.password" type="password" placeholder="请输入新密码" show-password></el-input>
        </el-form-item>
        <el-form-item prop="repassword">
          <el-input v-model="pwdData.repassword" type="password" placeholder="请确认新密码" show-password></el-input>
        </el-form-item>
      </el-form>
      <el-button style="width: 100%;" color="#c90000" @click="changePassword(formRefPwd)">修改</el-button>
    </div>

  </xwDialog>

  <el-dialog v-model="centerDialogVisible" width="500" center align-center>
    <template #title>
      <div style="text-align: left;">注销账号</div>
    </template>
    <span>
      该操作不可逆,您的账号一旦被删除成功将不可恢复
    </span>
    <template #footer>
      <div class="dialog-footer" style="display: flex; justify-content: right;">
        <el-button @click="dialogVisibleState">确认</el-button>
        <el-button type="primary" @click="centerDialogVisible = false">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang='ts' setup>

import { onBeforeMount ,onBeforeUnmount,reactive,ref} from 'vue';
import { userInfoStore } from '@/stores/userInfo';
import { userInfoAgain } from '@/hooks/user'
import { setUserAvatar, setModifyPhineCheckCode, modifyphone, modifyPassword, modifyPasswordGetSmsCode, checkSmsCodePwd, UserClear } from '@/api/user';
import { getLoginParam, getImageCode, type IimangCodeData } from '@/api/login'
import xwDialog from '@/components/dialog/index.vue';

import SlideSplit from '@/components/SlideSplit/index.vue'
const {userInfo} = userInfoStore()

import { ElNotification,ComponentSize, FormInstance, FormRules  } from 'element-plus'
import { log } from 'console';
//创建input标签

const dialogVisible = ref(false)
// 更换 绑定  微信 有bug
let srcDom :HTMLScriptElement|null=null;
const canceWeChat = ()=>{
  if(srcDom){
    console.log(srcDom);
    document.body.removeChild(srcDom)
    srcDom = null
  }
  // 创建标签
  srcDom = document.createElement('script')
  srcDom.src = 'http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
  document.body.appendChild(srcDom)
  srcDom.onload = async () => {
    // 加载完实例化对象
    let res = await getLoginParam()
    console.log(res); //请求的微信登录参数
    if (res.code != 0) return
    let { appid, redirectUri, state, scope } = res.data;
    var obj = new WxLogin({
      // self_redirect: false, // 是否自动跳转
      id: "code", //** 展示二维码的父容器id **/
      appid,//** 微信公众号appid **/
      scope,//作用域
      // redirect_uri: redirectUri, //重定向地址
      redirect_uri: decodeURIComponent(redirectUri),
      state,
      // style: "",
      // 样式需要base64编码
      href: "data:text/css;base64,LmltcG93ZXJCb3ggLnFyY29kZSB7d2lkdGg6IDIwMHB4O30NCi5pbXBvd2VyQm94IC50aXRsZSB7ZGlzcGxheTogbm9uZTt9DQouaW1wb3dlckJveCAuaW5mbyB7ZGlzcGxheTogbm9uZX0NCi5zdGF0dXNfaWNvbiB7ZGlzcGxheTogbm9uZX0NCi5pbXBvd2VyQm94IC5zdGF0dXMge3RleHQtYWxpZ246IGNlbnRlcjt9DQouaW1wb3dlckJveCAucXJjb2RlIHt3aWR0aDogMjMwcHg7bWFyZ2luLXRvcDogO2JvcmRlcjogbm9uZTt9DQo=",

    });

  }
  dialogVisible.value = true
}

// 、、更换手机号 
// 1.from
const formRef = ref<FormInstance>(); // 改为 null，因为你稍后会在模板中通过 ref 绑定它  
//类型接口
interface RuleForm {  
  phone: string;  
  phoneCode: string;  
}  
  // 、、2. 类型参数
const ruleForm = reactive<RuleForm>({  
  phone: '',  
  phoneCode: '',  
});
  //3.验证规则 
const rules = reactive<FormRules<RuleForm>>({  
  //普通规则  正则表达式规则  自定义规则
  phone: [  
    { required: true, message: '请输入手机号', trigger: 'blur' },  
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确格式的手机号', trigger: 'blur' },  
    {validator:(rule, value, callback)=>{
        if(value === userInfo.mobile){
          callback( new Error('不能与当前绑定手机号相同'))
        }else{
          callback();  
        }
      },
      trigger: 'blur'  
    } 
  ],
  //这个交给后端验证了
  // phoneCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }],  
});  

const setPhonenModel = ref(false);
// 激活取消更换手机号
const setSMSPhoneNumber = (type:boolean = true)=>{
  setPhonenModel.value = type
}

// 验证码的图片参数
// const rulesImg = reactive({
//     w:320,  // 大图的宽度 bigWidth
//     h:160,// 大图的高度 bigHeight
//     l:40,// 小图的宽度/ smallWidth
//     smallHeight="smallHeight //小图高
//     bigImg:'', //bigImageBase64
//     smImg:'', //smallImageBase64
// })
const imgInfo = reactive < IimangCodeData>({})
// 倒计时状态
interface ITimer{
  timerAPI: number|null;
  timerShow: boolean;
  outTime: number
}
const setTimer = reactive<ITimer>({
  timerAPI: null,
  timerShow : false,
  outTime :60
})
//定时器
const timer = (type:boolean = true)=>{
  if(type){
    setTimer.timerShow = type
    //加上window不报错
    setTimer.timerAPI =  window.setInterval(() => {
      if(setTimer.outTime < 1 ) {
        clearInterval(setTimer.timerAPI)
        setTimer.timerAPI = null
        setTimer.timerShow =false
        return 
      }else{
        setTimer.outTime--
      }
    }, 1000);
  }else{
    setTimer.timerShow =false
    clearInterval(setTimer.timerAPI)
    setTimer.timerAPI = null
  }
}

const rulesImgShow = ref(false)
// 获取验证图片
const getIMG = async()=>{
  let res = await getImageCode(ruleForm.phone) 
     console.log(res);
     if(res.code ===0){
      Object.assign(imgInfo,res.data)
      rulesImgShow.value = true
     }
}
//点击验证表单 
const sendPhoneCode =async (e:FormInstance | undefined)=>{
  console.log('整个from表单',e);
  if (!e) return
  await e.validate( async(valid, fields) => {
    if (valid) {
      // 验证通过掉接口
      getIMG()
    } else {
      console.log('error submit!', fields)
    }
  })
}
// 、、用户行为验证验证
const mouseMoveEnd =async (e:string)=>{
let res = await setModifyPhineCheckCode(e,ruleForm.phone)
  console.log(res);
    if(res.code === 0 || res.code === 5){
      ElNotification({
        type:res.code==0?'success':'warning',
        message: res.data ?? res.errorMessage
      })
      timer()
      rulesImgShow.value = false
    }else{
      ElNotification({
        type:'error',
        message:res.errorMessage
      })
      getIMG() //不通过重新验证
    }
}
//修改手机号最终结果
const checkPhoneCode =async ()=>{

  let res = await modifyphone(ruleForm.phone,ruleForm.phone)
  console.log(res);
  if(res.code ===0){
    //更新
    userInfoAgain(userInfoStore().token)    
    setSMSPhoneNumber(false)
    ElNotification({
      type:'success',
      message:res.data
    })
  }else{
    ElNotification({
      type:'warning',
      message:res.errorMessage
    })
  }
}


// 更换头像
const avatarInput = ref<HTMLElement | null>(null)
console.log(userInfo);

// 、更换头像 5M太大 帮用户压缩头像 后续实现
const setUserAvatarApi = ()=>{3
  avatarInput.value && avatarInput.value.click()
}
const uploadImage = async (e:Event) => {
  //此处做一些判断 图片后缀  大小等
  const imgType = /.*?\.(jpg|jpeg|png|gif|bmp|webp)/
  const imgSizeMax = 5 * 1024 * 1024
  console.log('选中的图片内容',e.target.files[0]);
  let img = e.target.files[0]
  // 创建文件对象
  if(img.size > imgSizeMax || !imgType.test(img.name) ){
    ElNotification.error({

    message: '图片大于5M或格式不支持',
    showClose: false,
  })
  return
  }
  const formData = new FormData()
  // 添加到对象中
  formData.append('file',img)
  const res = await setUserAvatar(formData)
  console.log(res);
  if(res.code===0){
    //直接改本地  少走一遍请求
    userInfoStore().userInfo.logo = res.data
    ElNotification.success({
    message: '修改信息成功',
    showClose: false,
  })
  }
}

//修改密码的短信验证码
const getSmSCheckPwd = ref(false)
const SmsCodePwd = ref('')
const setSmSCheckPwdModelStart = (type:boolean = true)=>{
  getSmSCheckPwd.value = type
}
// 获取短信验证码 '修改密码'
const getSmSCheckPwdApi =  async()=>{
  timer()
  let res = await modifyPasswordGetSmsCode()
  //接口验证未通过 405  不用了 直接改状态
  if(res.code ===0){
    ElNotification({
      type:'success',
      message:res.data
    })
    
  }else{
    ElNotification({
      type:'error',
      message:res.errorMessage
    })
  }
}

// 验证短信验证码
const checkSmsCodePwdApi = async()=>{
  console.log(SmsCodePwd.value);
  
  let res = await checkSmsCodePwd(SmsCodePwd.value)
  console.log(res);
  
  if(res.code ===0){
    passwordModelState(true)
    ElNotification({
      type:'success',
      message: res.errorMessage
    })
    passwordModelState(false)
  }else{
    ElNotification({
      type:'error',
      message:res.errorMessage
    })
  }
}

// 修改密码
const passwordModel = ref(false)
const passwordModelState =(type:boolean=true)=>{
  if(type === true) {
    setSmSCheckPwdModelStart(false)
  }
  passwordModel.value = type
}
const formRefPwd = ref<FormInstance>();
interface IpwdData {
  password: string;
  repassword: string
}
const pwdData = reactive<IpwdData>({
  password: '',
  repassword: ''
})
//验证规则
const ruleFormPwd = reactive<FormRules<IpwdData>>({
    password:[
      { required: true, message: '请输入新密码', trigger: 'blur' },
      { min: 6, max:18, message: '密码不能小于6位大于18位', trigger: 'blur' },
      {
        pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,18}$/,message: '密码必须包含数字和字母', trigger: 'blur'
      }
    ],
    repassword:[{
      validator: (rule, value, callback) => {
        if (value !== pwdData.password) {
          callback(new Error('请输入相同密码'))
        } else if(value === ''){
          callback(new Error('请确认密码'))
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
    ]
  }
)
//修改密码
const changePassword = (e:FormInstance)=>{
  console.log(e);
  console.log(e.validate);
        e.validate( async(valid, fields) => {
          if (valid) {
            let res = await modifyPassword(pwdData.password,pwdData.repassword)
            console.log(res);
            if(res.code === 0){
              ElNotification({
                type:'success',
                message:res.data
              })
              passwordModelState(false)
            }else{
             ElNotification({
               type: 'warning',
               message: res.errorMessage
             })
            }
          }
        })
      }


      // 删除账号
// const centerDialogVisible = ref(false)
// const UserClearApi =  async()=>{
//   dialogVisibleState.value = true


  // await UserClear()
// }
// 删除账号
const centerDialogVisible = ref(false)
const dialogVisibleState = async ()=>{
  let res = await UserClear()
  console.log(res);
  userInfoStore().outLogin()
  if(res.code== 0){
    ElNotification({
      type:'success',
      message:res.data
    })
  }else{
    ElNotification({
      type:'warning',
      message:res.errorMessage
    })
  }
} 
      
//打扫战场
onBeforeUnmount(()=>{
  timer(false)
  rulesImgShow.value = false
})


</script>
<style scoped lang='scss'>

.red {
  color: #c90000 !important;
}

.titleText{
  font-size: 1vw;
  font-weight: 700;
}
.userInfo{
      display: flex;
        align-items: center;
  font-size: 1vw;
      padding: 0.5vw 0;
      font-weight: 700;
  p{
    margin-right: 40px;
  }
  .logoAvatar {
  cursor: pointer;
    width: 4vw;
    border-radius: 50%;
    }

}

.userInfoList{
  display: flex;
  font-size: 1vw;
  flex-direction: column;
  p{
        font-weight: 700;
        span{
          font-weight: 400;
          color: gray;
        }
  }

  ul {
    border: .1vw solid #DBDBDB;
    border-radius: 0.5vw;
    padding: 0 0.5vw;
      li {
          display: flex;
          justify-content: space-between;
          padding: 1vw 0.5vw;
          align-items: center;
          >div {
            display: flex;
            img{
              margin-right: 0.5vw;
            }

            span {
              color: gray;
            }
          }
        }

        &> :first-child {
          border-bottom: 1px solid gray;
        }
  }



}

.setPwd{
  font-weight:400;
  color: #232323;
  font-size: 30px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .pwdTip{
            width: 306px;
              font-size: 18px;
              line-height: 27px;
              text-align: center;
              color: #6b6b6b;
   }
   .mymobile{
   
      line-height: 27px;
      font-size: 18px;
      width: 100%;
      text-align: left;
   }
}

</style>
